<?php

include('libs/nusoap.php');
ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL cache

define('TMP_PATH', 'c:/tmp/');
define('JODConverter', 'c:/lib/jodconverter-cli-2.2.2.jar');

if (function_exists(@date_default_timezone_set)) {
    @date_default_timezone_set('Asia/Bangkok');
}

$server = new soap_server();
$namespace = "urn:documentconverster";
$WSDL = "documentconverster";

$server->configureWSDL($WSDL, $namespace);

// ---------------- Register Method ------------------------------------------
$server->register('Convert', array('bytes' => 'xsd:unsignedByte[]', 'type' => 'xsd:string'), array('return' => 'xsd:unsignedByte[]'), $namespace, $namespace . '#Converst', 'rpc', 'encoded', 'Document Converster');

$server->register('Hello', array('name' => 'xsd:string'), array('return' => 'xsd:string'), $namespace, $namespace . '#Hello', 'rpc', 'encoded', 'Hello');

// ---------------- Public Method --------------------------------------------
function Convert($document_bytes, $type) {
    //begin convert
    $content = "";
    $unique = md5(microtime());
    
    if(!is_dir(TMP_PATH)){
        @mkdir(TMP_PATH);
        @chmod(TMP_PATH, 755);
    }
    
    $temp = TMP_PATH . $unique . '.odt';
    $temp_out = TMP_PATH . $unique . '.' . $type;
    file_put_contents($temp, base64_decode($document_bytes));

    // run conver tool
    $cmd = sprintf("java -jar  %s  %s  %s", JODConverter, $temp, $temp_out);
    exec($cmd);
    if (file_exists($temp_out)) {
        $content = file_get_contents($temp_out);
        @unlink($temp_out);
        @unlink($temp);
        return base64_encode($content);
    } else {
        @unlink($temp);
        $content = "";
        return base64_encode($content);
    }
}

function Hello($name) {
    return 'Hello ' . $name;
}

// ---------------- Response -------------------------------------------------
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
